
<!DOCTYPE html> 
<html> 
	<head> 
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1 maximum-scale=1.0">   
	<title>Platforms Near Me</title> 
	<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
  <script type="text/javascript">
    var googAnalytics = null;
    var currentPlatforms = null;
    var mapObj = null;
    var selectedFeature = null;
  </script>

	<link rel="stylesheet" href="http://rcoos.org/resources/lib/jquery.mobile/jquery.mobile-1.0rc2.min.css" />
	<script type="text/javascript" src="http://rcoos.org/resources/lib/jquery.mobile/plugins/geoLocator.js"></script>  
	<script src="http://rcoos.org/resources/lib/jquery.mobile/jquery.mobile-1.0rc2.js"></script>
	<link rel="stylesheet" href="http://rcoos.org/resources/css/style.mobile.css" />
	<link rel="stylesheet" href="http://rcoos.org/resources/css/style.mobile-jq.css" />
  <script src="http://rcoos.org/resources/lib/OpenLayers-2.11/OpenLayers.mobile.js" type="application/x-javascript" charset="utf-8"></script>
  
  <script src="http://rcoos.org/resources/lib/jsUtils.js" type="application/x-javascript" charset="utf-8"></script>
  <script src="http://rcoos.org/resources/lib/mobileMap.js" type="application/x-javascript" charset="utf-8"></script>
  <script type="text/javascript">
    var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
    document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
  </script>
  
  <style type="text/css">    
    .srchForm .ui-field-contain { margin: 0.5em 0; padding: 0em 0;}
    .my-list .ui-select,
    .my-list label.ui-input-text  { vertical-align: top;   }
    .my-list label.ui-select,
    .my-list label.ui-input-text { display: inline-block;  width: 30%;  margin: 0 2% 0 0; }
    .my-list input.ui-input-text, 
    .my-list textarea.ui-input-text, 
    .my-list .ui-select, 
    .my-list .ui-input-search { width: 60%; display: inline-block; }
    
    .obs label.left{
      width:120px;
      float:left;
    }        
    .obs label.right{
      width:120px;
      #float:left;
    }        
    
  </style>
    <!--
    .ui-page {
      background: url(http://rcoos.org/resources/images/default/secoora_logotext.png);
      background-attachment:fixed;
      background-repeat: no-repeat;
      background-size: 100%;      
    }
    -->
</head> 
<body> 

<div id="mainPage" data-role="page" data-theme="b">
  <!-- /header -->
	<div data-role="header" id="homeHeader" name="homeHeader" data-theme="b">
		<h1>Find Platforms</h1>
	</div>
	<div data-role="content" id="homeContent" name="homeContent">	
  <div class="ui-br"><img src="http://carolinasrcoos.org/images/rcoos_hdr_transparent.gif" width="100%" height="85" alt="header"></div>
    <form id="srchForm" class="srchForm">
      <div class="my-list" id="latDiv" data-role="fieldcontain">
        <label for="lat">Latitude</label> 
        <input id="lat" type="text" id='lat' value="Locating">
      </div>    
      <div class="my-list" id="lonDiv" data-role="fieldcontain">
        <label for="lon">Longitude</label>
        <input id="lon" type="text" id='lon' value="Locating">
      </div>        
      <div class="my-list" id="radiusDiv" data-role="fieldcontain">
          <label for="radiusCombo">Search Radius(nm)</label>
          <select id="radiusCombo" onchange="">
              <option value ="Radius">Radius</option>
              <option value ="1">1</option>
              <option value ="5">5</option>
              <option value ="10">10</option>
              <option value ="20">20</option>
              <option value ="30">30</option>
              <option value ="50">50</option>
              <option value ="100">100</option>
          </select>
      </div>                
      <div id="submitDiv" data-role="fieldcontain">    
        <a href="#platformsResultsPage" type="button" data-role="button">Search</a>
      </div>
    </form>
	</div><!-- /content -->
	<div data-role="footer" id="homeFooter" name="homeFooter" data-theme="b">
	</div><!-- /footer -->
</div><!-- /page -->

<div data-role="page" id="platformsResultsPage" data-theme="b">
  <div data-role="header" data-add-back-btn="true" id="resultsHeader" data-theme="b">
    <h1>Platform Locations</h1>
  </div><!-- /header -->
  <div data-role="content" id="resultsContent">	
  </div>
	<div data-role="footer" id="resultsFooter" data-theme="b">
	</div><!-- /footer -->  
</div><!-- /page -->

<div data-role="page" id="mapPage" data-theme="b">
  <script type="text/javascript">
  //Called when the page first initializes.
  $("#mapPage").live('pageinit', function(e) {      
    // Map zoom in (+)
    $("#plus").click(function(){          
      if(mapObj !== null)
      {
        mapObj.map.zoomIn();
      }
    });
    // Map zoom out (-)
    $("#minus").click(function(){
      if(mapObj !== null)
      {
        mapObj.map.zoomOut();
      }        
    });
    
    //The popup page is for showing the data for the station the  user has clicked on.
    $('#popup').live('pageshow',function(event, ui){
        // Set the H1(title portion) of the header to be the station name.
        var h1 = $('#popup').find('div:jqmData(role="header") h1').html(mapObj.selectedFeature.attributes['staID'] );
        var li = "";
        for(var i = 0; i < mapObj.selectedFeature.attributes.obsList.length; i++)
        {
          var obs = mapObj.selectedFeature.attributes.obsList[i];
          var html = "";
          if(i === 0)
          {
            html = "<div style='width:50%;float:left'>Time" + "</div><div style='width:50%;float:right'>" + obs['time'] + "</div>";                  
            li += '<li>' + html + '</li>';
          }
          html = "<div style='width:50%;float:left'>" + obs['obsTypeDesc'] + "</div><div style='width:50%;float:left'>" + obs['value'] + ' ' + obs['uomType'] + "</div>";
          li += '<li>' + html + '</li>';
        }
        $("ul#details-list").empty().append(li).listview("refresh");
    });    
  });
  function fixMapContentHeight()
  {    
    // fix height of content            
    var header = $("div[data-role='header']:visible"),
        content = $("div[data-role='content']:visible:"),
        viewHeight = $(window).height(),
        contentHeight = viewHeight - header.outerHeight();
    var pos = $(window).scrollTop();
    if ((content.outerHeight() + header.outerHeight()) !== viewHeight) {
        contentHeight -= (content.outerHeight() - content.height() + 1);
        content.height(contentHeight);
    }
    if(mapObj) 
    {
      mapObj.map.updateSize();
    } 
  }
  $("#mapPage").live("pagehide", function(e, data) {     
    var npID = data.nextPage.attr('id');
    if(npID !== 'popup')
    {
      var $target = $(e.target);
      var pageId = '#' + $target.attr('id');
      //Finished with the map.
      mapObj = null;            
      //Get all the previous predictions and remove their nodes.
      $("#map").html("");
    }
  });
  $("#mapPage").live("pageshow", function(e) {
    fixMapContentHeight();
    if(mapObj === null)
    {
      var lat = $("#lat").val();
      var lon = $("#lon").val();
      var mapOptions = {};
      mapOptions["mapConfig"] = 
      {
        mapExtents : 
        {
          lowerLeft : 
          {
            lon : -90.5,
            lat : 24.5
          },
          upperRight : 
          {
            lon : -60.5,
            lat : 37.2
          },
          zoomToExtent :
          {
            lowerLeft: 
            {
              lon : -90.5,
              lat : 24.5
            },
            upperRight: 
            {
              lon : -60.5,
              lat : 37.2
            }            
          },          
          centerMapOn :
          {
            lon : lon,
            lat : lat
          }
        },
        maxResolution: 156543.0339,
        projection: "EPSG:900913",
        displayProjection: "EPSG:4326",
        units: "degrees"
      };
    
      //Create the map object.
      mapObj = new OpenLayers.mobileMap({div: "map", mapOptions: mapOptions});
      //Size the map to the content area.
      mapObj.map.updateSize();
      if(currentPlatforms.features.length)
      {        
        mapObj.addStations("Platforms", currentPlatforms);
      }
      mapObj.addCurrentLocationMark(lon,lat);
    }
    $("#mapPage").bind("resize orientationchange", function(e) {
      fixMapContentHeight();
    });
    setTimeout(function() {
        $(window).scrollTop(0);
     }, 20 );    
    
  });     
  </script>  
  <div class="mappage" data-role="header" data-add-back-btn="true" id="mapHeader" data-theme="b">
    <h1>Platforms</h1>
  </div>  
  <div data-role="content" id="mapContent">	
    <div id="map"></div>
  </div>
  <div class="mappage" id="navigation" data-role="controlgroup" data-type="vertical">
    <a href="#" data-role="button" data-icon="plus" id="plus"
       data-iconpos="notext"></a>
    <a href="#" data-role="button" data-icon="minus" id="minus"
       data-iconpos="notext"></a>
  </div>
</div>
<div id="popup" data-role="dialog" data-theme="b">
  <div data-position="inline" data-theme="b" data-role="header">
      <h1>Details</h1>
  </div>
  <div data-theme="b" data-role="content">
      <ul id="details-list" data-role="listview">
      </ul>
  </div>
</div>

<div id="noPlatformsDlg" data-role="page" data-theme="b">	
  <div data-role="header" data-theme="b">
    <h1>No Platform found</h1>
  </div>

  <div data-role="content" data-theme="b">
    <p>No platforms found in the radius around your current location. Try using a greater radius.</p>
  </div>
</div>


<script type="text/javascript">
   $(document).ready(function() {
    //Enable the back button in the header.
    $.mobile.page.prototype.options.addBackBtn = true;    
    //$.mobile.page.prototype.options.ajaxEnabled = false;
    $.geo("locate",function(position){
      // returns object of type Position
      // see http://dev.w3.org/geo/api/spec-source.html#position_interface
      $("#lat").val(position.coords.latitude);
      $("#lon").val(position.coords.longitude);
    },
    function(error, message){
      // returns error object of type PositionError
      // see http://dev.w3.org/geo/api/spec-source.html#position_error_interface
      // and human readable message in text
      $("#lat").val(message);
      $("#lon").val(message);
    });
    googAnalytics = new googleAnalytics("UA-3867608-4");
    if(googAnalytics.getTracker() !== null)
    {
      //Track the page view
      googAnalytics.trackPageView();
    }
    
  });
  // Listen for any attempts to call changepage.
  $(document).bind( "pagebeforechange", function( e, data ) {
    // We only want to handle changepage calls where the caller is
    // asking us to load a page by URL.
    if ( typeof data.toPage === "string" ) {
      // We are being asked to load a page by URL, but we only
      // want to handle URLs that request the data for a specific
      // category.
      var u = $.mobile.path.parseUrl( data.toPage );
      if(u.hash.search(/^#platformsResultsPage/) !== -1) {
        //var fromPage = $.mobile.path.parseUrl(data.options.fromPage[0].baseURI);
        if(data.options.fromHashChange == false)
        {
          //Show the page loading icon since we have to query the server for data.
          $.mobile.showPageLoadingMsg();
          //Tell jquery we are handling the event and to do no further processsing.
          e.preventDefault();
          getPlatforms(u, data.options);
        }
      }
      else if(u.hash.search(/^#obsResults_/) !== -1) {
        e.preventDefault();     
        var pageSelector = u.hash.replace( /\?.*$/, "" );
        var $obsPage = $(pageSelector);
        $obsPage.page();
        data.options.dataUrl = u.href             
        $.mobile.changePage($obsPage, data.options);  
        if(googAnalytics !== null)
        {
          var station = pageSelector.replace("#obsResults_", "");
          googAnalytics.trackEvent("Mobile Buoy", "Click", station);
        }                  
        
      }
    }
  });
  $(document).bind( "pagecreate", function(event) {
    event;
  });
  
  function getPlatforms(urlObj, options)
  {
    var radius = $("#radiusCombo").val();
    var lat = $("#lat").val();
    var lon = $("#lon").val();
    
    if(lat.length && lon.length)
    {                 
      var url = "./proxy-bin/AjaxProxyRev2.php?url=http://neptune.baruch.sc.edu/python_tst/getBuoy.py/handler";
      var jq = $.getJSON(url, {radius: radius, latitude: lat, longitude: lon}, function(data)
      {
        $.mobile.hidePageLoadingMsg();
        currentPlatforms = data;
        if(data != null && data.features.length)
        {
          //Get all the previous platforms and remove their nodes.          
          var children = $('div[id^="obsResults_"]');
          if(children.length)
          {
            for(var i = 0; i < children.length; i++)
            {
              var id = children[i].getAttribute('id');
              $('#' + id).remove();
            }
          }
          //Results of the search go into the platformsResultsPage page.
          var $resPage = $("#platformsResultsPage");
          // Get the header for the page.
          var $header = $resPage.children( ":jqmData(role=header)" );
          // Get the content area element for the page.
          var $content = $resPage.children( ":jqmData(role=content)" );
          
          var platforms = data.features;
          //First loop through, create the individual platform list.
          if(platforms.length > 0)
          {
            var html = "";
            
            //We add a new <ul> which will then get populated with <li> entries that represent the individual platforms.
            html += "<ul id=\"platforms_ul\" class=\"ui-listview\" data-role=\"listview\" data-inset=\"true\">";
            for(var i = 0; i < platforms.length; i++ )
            {
              //Create the list for the indivdual platforms. 
              var platform = platforms[i];
              var platformParts = platform.properties.staID.split('.');
              var org = platformParts[0].toUpperCase();
              var text = org + ' ' + platformParts[1] + ' ' + platform.properties.distance + '(' + platform.properties.distanceUnits + ')';
              if(i == 0)
              {
                //First entry will be a button to map the results. Map will be centered on current location
                html += "<li><a href=\"#mapPage\">Map Platforms</a></li>";
              }
              html += "<li><a href=\"#obsResults_"+ platformParts[1] +"\">"+ text + "</a></li>";
              if(platform.properties.obsList != undefined)
              {
                var obsDiv = "<div data-role=\"page\" id=\"obsResults_"+platformParts[1]+"\">";

                //
                //Add a new <ul> which will contain entries for the individual platform observations.
                obsDiv += "<div data-role=\"header\" id=\"hdr_" + platformParts[1] + "\"><h1>" + org + ' ' + platformParts[1] + "</h1></div>";
                obsDiv += "<div data-role=\"content\" id=\"content_" + platformParts[1] + "\">";
                obsDiv += "<ul id=\"" + org + ' ' + platformParts[1] + "\" class=\"obs ui-listview\" data-role=\"listview\" data-inset=\"true\">";
                var obsList = platform.properties.obsList;
                for(var j = 0; j < obsList.length; j++)
                {
                  var obs = obsList[j];
                  if(j === 0)
                  {
                    text = "<label class=\"left\">Time" + "</label><label class=\"right\">" + obs['time'] + "</label>";                  
                  }
                  else
                  {
                    text = "<label class=\"left\">" + obs['obsTypeDesc'] + "</label><label class=\"right\">" + obs['value'] + ' ' + obs['uomType'] + "</label>";
                  }
                  obsDiv += "<li>" + text + "</li>";
                }
                obsDiv += "</ul></div>"
                $(obsDiv).appendTo('body');
              }              
            }
            $content.html(html);
          }
          else
          {
            $content.html("<ul id=\"platforms_ul\" class=\"ui-listview\" data-role=\"listview\" data-inset=\"true\"><li><label>No Platforms Found</label></li></ul>");
          }
          $resPage.page();
          // Enhance the listview we just injected.
          $content.find( ":jqmData(role=listview)" ).listview();           
          // We don't want the data-url of the page we just modified
          // to be the url that shows up in the browser's location field,
          // so set the dataUrl option to the URL for the category
          // we just loaded.
          //options.dataUrl = urlObj.href;
          // Now call changePage() and tell it to switch to
          // the page we just modified.          
          $.mobile.changePage($resPage);
          $header.show();
          $content.show();
        }
        else
        {
          $.mobile.changePage("#noPlatformsDlg");        
        }
      });
      jq.error(function() {
        $.mobile.hidePageLoadingMsg();
        alert("Unable to retrieve the platforms near you. Please try again.");
      });
    }
  }               
</script>


</body>
</html>
